//当用户登录后 返回一个唯一的标识
let express = require('express');
let app = express();
let path = require('path'); //拼接路径
app.use(express.static(path.join(__dirname,'public')));
app.use(express.static(path.join(__dirname)));  //以当前根目录为静态目录加载

let cookieParser = require('cookie-parser');
app.use(cookieParser());  //req.cookies['connect.sid']  获取cookies

let svgCaptcha = require('svg-captcha')   //验证码

let bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended:true}))       //a=1&b=2 变成 {a:1,b:2} 挂载在req.body上
//
let userList = [{username:'zf',password:'zf',money:100},{username:'jw',password:'jw',money:102}]
let SESSION_ID = 'connect.sid';     //名称：id
let session = {};
//
app.post('/api/login',function(req,res){
    let {username,password} = req.body;
    console.log(username,password)
    let user = userList.find(user=>(user.username===username)&&(user.password===password))
    if(user){
        //服务区需要在用户登录后 给个信息
        let cardId = Math.random() + Date.now();
        session[cardId] = {user};      //{id:{user:{username:'1',password:'1'}}}
        res.cookie(SESSION_ID,cardId,{httpOnly:false});   //{httpOnly:true}
        res.json({code:0});
    }else{
        res.json({code:1,error:'用户不存在'})
    }
})

// 反射型  http://localhost:3000/welcome?type=你好   xss屏蔽
//{httpOnly:true}  一般情况下会让cookie在前端不可以获取 这不是解决xss的方案 只是降低受损范围
//查询参数 可以加上encodeURIComponent 方式解决
app.get('/welcome',function(req,res){
    res.send(`${encodeURIComponent(req.query.type)}`);
})


//用户评论信息
let comments = [{username:'zf',content:'今年考研国家线突破天际'},{username:'zs',content:'选择很重要'}]
app.get('/api/list',function(req,res){
    res.json({code:0,comments})
})

//当你访问添加留言时  就执行到这里
app.post('/api/addcomment',function(req,res){
    let r = session[req.cookies[SESSION_ID]] || {}    //{user:{username,password}}
    let user = r.user
    if(user){   //这个人登录过
        comments.push({username:user.username,content:req.body.content});
        res.json({code:0} )
    }else{
        res.json({code:1,error:'用户未登录'})
    }
});
// xss存储型 恶意的脚本存储到了服务器上，所有人访问时都会造成攻击， 比反射型和DOM-Based 范围更大


//获取用户信息
app.get('/api/userinfo',function(req,res){
    let r = session[req.cookies[SESSION_ID]] || {}    
    //data表示的是 svg text表示的是验证码对应的结果
    let {data,text} = svgCaptcha.create();
    r.text = text;  //下次请求时应该拿到返回的结果和上次存好的结果做对比
    let user = r.user
    if(user){ 
        res.json({
            code:0,
            user: 
            {
                username:user.username,
                money:user.money,
                svg:data,    //验证图形
            }
        })
    }else{
        res.json({code:1,error:'用户未登录'})
    }
})


//转账
app.post('/api/transfer',function(req,res){
    let r = session[req.cookies[SESSION_ID]] || {}    
    let user = r.user
    //不靠谱 可以通过node自己发请求来实现伪造  
    let referer = req.header['referer'] || '';
    if(referer.includes('http://localhost:8000')){
        if(user){ 
            let {target,money,code,token}=req.body;
            if('my'+ req.cookies[SESSION_ID]=== token){
                if(code&code===r.text){
                    //转钱逻辑
                    money = Number(money)
                    userList.forEach(u=>{
                        if(u.username === user.username){
                            u.money-=money;
                        }
                        if(u.username === target){
                            u.money+=money;
                        }
                    });
                    res.json({code:0});
                }else{
                    res.json({code:1,error:'验证码不正确'})
                }
            }
        }else{
            res.json({code:1,error:'用户未登录'})
        }
    }else{
        res.json({code:1,error:'被人攻击了'})
    }
})

app.listen(8000);

//xss + csrf = xsrf
//跨站请求伪造  钓鱼网站
  